/*
Copyright (C) 2022-2024 Inspur Corp.

SPDX-License-Identifier: Apache-2.0
*/
package logger

import (
	"fmt"
	"github.com/op/go-logging"
	"icep/common/file"
	"os"
)

const LogLevelKey = "ICEP_LOG_LEVEL"

var LogLevel string

func GetLogger(module string) *logging.Logger {
	var log = logging.MustGetLogger(module)

	var format = logging.MustStringFormatter(
		`[%{level:.5s}][%{module}] %{time:2006-01-02 15:04:05} [%{longfunc}] : %{message}`,
	)

	logBackend := logging.NewLogBackend(os.Stderr, "", 0)
	logBackendFormat := logging.NewBackendFormatter(logBackend, format)
	logBackendLeveled := logging.AddModuleLevel(logBackendFormat)
	switch (os.Getenv(LogLevelKey)) {
	case "INFO": logBackendLeveled.SetLevel(logging.INFO, module); break;
	case "DEBUG": logBackendLeveled.SetLevel(logging.DEBUG, module); break;
	case "WARNING": logBackendLeveled.SetLevel(logging.WARNING, module); break;
	case "ERROR": logBackendLeveled.SetLevel(logging.ERROR, module); break;
	default: logBackendLeveled.SetLevel(logging.DEBUG, module);
	}
	logging.SetBackend(logBackendLeveled)

	return log
}

func GetFileLogger(filePath string) *logging.Logger {
	var log, _ = logging.GetLogger("icep")
	err := file.CreateIfNotExists(filePath, false)
	if err != nil {
		fmt.Errorf("file create error: %s", filePath)
	}
	logFile, err := os.OpenFile(filePath, os.O_CREATE | os.O_APPEND | os.O_WRONLY | os.O_SYNC, os.ModePerm)
	if err != nil {
		fmt.Errorf("file open error: %s", err.Error())
	}

	var format = logging.MustStringFormatter(
		`%{time:2006-01-02 15:04:05} %{shortfunc} > %{level:.4s} %{id:03x}%{color:reset} %{message}`,
	)
	logBackend := logging.NewLogBackend(logFile, "", 0)
	logBackendFormat := logging.NewBackendFormatter(logBackend, format)
	logBackendLeveled := logging.AddModuleLevel(logBackendFormat)
	logBackendLeveled.SetLevel(logging.INFO, "")
	log.SetBackend(logBackendLeveled)

	return log
}